#!/usr/local/bin/python3.6
# coding:utf-8
# @Time    : 2019/11/2 15:13
# @Author  : ZhangBing
# @Email   : 18829272841@163.com
# @File    : post.py
# @Software: PyCharm
from flask import Blueprint, request, render_template, session, make_response, redirect, url_for
from modules import User, Post
from utils import getlogger, login_auth
from exts import db

post = Blueprint('post', __name__)
log = getlogger('post')


@post.route('/pub', methods=['POST', 'GET'])
@login_auth
def pub():
    if request.method == 'POST':
        if request.is_json:
            data = request.json
        else:
            data = request.form
        post = Post(title=data['title'], content=data['content'], author_id=session.get('id'))
        try:
            db.session.add(post)
            db.session.commit()
            log.info('{}  文章{}添加成功'.format(post.id, post.title))
            return redirect(url_for('post.getall'))
        except  Exception as  e:
            log.error("文章{}添加失败".format(post.title))
    return render_template('pub.html')


@post.route('/<id>')  # 此处用于显示详情页面
def get(id):
    try:
        query = Post.query.filter(Post.id == id)
        q = query.first()
        if query.count():
            user = User.query.filter(User.id == q.author_id).first()
            print(user)
            context = {'title': q.title, 'content': q.content, 'create_time': q.create_time, 'author': user.username}
            return render_template('get.html', **context)
        else:
            return make_response("id: {}  not exits".format(id))
    except  Exception  as e:
        pass


@post.route('/')
def getall():  # 此处用于显示所有文章基本配置和链接,此处可携带相关page和size进行处理
    size = request.args.get('size')
    page = request.args.get('page')
    if size and 0 < int(size) < 20:
        size = int(size)
    else:
        size = 10
    if page and 0 < int(page):
        page = int(page)
    else:
        page = 1
    start = size * (page - 1)
    # q=Post.query.order_by(Post.id.desc()).all()[start:page*size]  # 此处是一个列表
    q = Post.query.all()[::-1][start:page * size]  # 此处是一个列表,进行逆序排列
    content = {'content': q}
    return render_template('getall.html', **content)


# 查看功能完善,此处使用args的拼接方式进行处理
@post.route('/search')
def search():
    q = request.args.get('q')  # 此处获取key，及get对应的key
    query = Post.query.filter((Post.title.like("%{}%".format(q)))).all()  # 此处只对博客名称进行处理
    content = {'content': query}
    return render_template('getall.html', **content)


if __name__ == "__main__":
    pass
